///
/// Made and Tested by Evan McCullough
/// COE 1186
/// March 15, 2011
/// Last tested: March 23, 2011
/// AutoBiographyGUI
///

import javax.swing.*;
import java.awt.*;
import java.util.*;
import javax.swing.plaf.basic.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.imageio.*;
import javax.*;
import java.io.*;
import java.awt.event.*;
import java.sql.*;

public class AutoBiographyGUI implements Runnable{
    //Kadded updatePanel for update user info
  JPanel graphicsPanel, diagnosticsPanel, buttonPanel, middlePanel, updatePanel, logoPanel, rightPanel, fillerPanel;
  JFrame mainWindow;
  Container thePane;
  Image car, tablePic, logo, updatePic, tablePic2;
  JLabel carPic, carName, table;
  JTextArea fillerLabel;
  StatsTable myTable;
  AutoListener theListener;
    //Kadded changeinfo for update user info
  JButton upload, retrieve,change, run, halt, quit, select, recordSubmit, updatebut, convertButton;
  JComboBox carChange, diagType, oldRecords;
  JMenuItem car1, car2;
  String ford, buick, engine, fuel, rpm, sysDisplayed, toWhat;
  boolean running = true;
  boolean pop = false;
  int rows, cols, testNum=1;
  String[] columnNames, specificStats;
  String [][] oldTable;
  String [][] newTable;
  String [][] rowData;
  Thread watchTable, populate,listSelector;
  JList list, statList;
  AutoBiographyGUI selfref;
  JScrollPane paneintheass;
  
  int ntype=0;

  JMenuBar menuBar;
  JMenu fileMenu, helpMenu, submenu;
  JMenuItem open, selectDiagnostic, quitGUI, helper, settings,blue, cyan, lightGray, orange, green, pink;
  JRadioButton tableRB, graphRB;
  ButtonGroup viewButtons;

  ResultSet statRS;

  User currUser;
  Car currCar;

  // BlueReader object that can generate dummy statistics.
  bluereader br;

  public Connection dbConnection = null;
  //public String connectString = "jdbc:mysql://ec2-184-73-248-31.compute-1.amazonaws.com:3419/AutoBiography";
  //public String driver = "com.mysql.jdbc.Driver";
  //public String userid = "Team_AutoLytics";
  //public String pwd = "COE1186";
  public Statement stmt = null;



  public AutoBiographyGUI(User curr, Car current_car, Connection connect){
    dbConnection = connect;
    selfref = this;
    currUser = curr;
    currCar = current_car;
    theListener = new AutoListener();
    
    GridBagConstraints c = new GridBagConstraints();

    System.out.println(currCar.vin);

    try{
      stmt = dbConnection.createStatement();
    }catch(SQLException stmtE){
      System.out.println("GUI statement error"+stmtE);
    }
    menuBar = new JMenuBar();

    fileMenu = new JMenu("File");
    menuBar.add(fileMenu);

    settings = new JMenuItem("Settings");
    settings.addActionListener(theListener);
    fileMenu.add(settings);

    quitGUI = new JMenuItem("Quit");
    quitGUI.addActionListener(theListener);
    fileMenu.add(quitGUI);

     //COLOR SCHEME FOR BUILD 3
    submenu = new JMenu("Change Color Scheme");
    blue = new JMenuItem("BLUE");
    submenu.add(blue);
    blue.addActionListener(theListener);

    cyan = new JMenuItem("CYAN",ActionEvent.ALT_MASK);
    cyan.addActionListener(theListener);
    submenu.add(cyan);

    green = new JMenuItem("GREEN",ActionEvent.ALT_MASK);
    submenu.add(green);
    green.addActionListener(theListener);
    
    lightGray = new JMenuItem("LIGHT_GRAY",ActionEvent.ALT_MASK);
    submenu.add(lightGray);
    lightGray.addActionListener(theListener);
    
    orange = new JMenuItem("ORANGE",ActionEvent.ALT_MASK);
    orange.addActionListener(theListener);
    submenu.add(orange);
    
    pink = new JMenuItem("PINK",ActionEvent.ALT_MASK);
    submenu.add(pink);
    pink.addActionListener(theListener);
    menuBar.add(submenu);


//     helpMenu = new JMenu("Help");
//     menuBar.add(helpMenu);
    
//     helper = new JMenuItem("Help...");
//     helper.addActionListener(theListener);
//     helpMenu.add(helper);

    graphicsPanel = new JPanel();
    graphicsPanel.setLayout(new GridBagLayout());
    graphicsPanel.setSize(1200, 800);
    graphicsPanel.setBackground(Color.white);
    graphicsPanel.setBorder(new EtchedBorder(Color.gray, Color.black));

    //Systems List
    JPanel leftPanel = new JPanel();
    leftPanel.setLayout(new GridLayout(1, 1));
    leftPanel.setSize(300, 800);
    leftPanel.setBackground(Color.white);
    leftPanel.setBorder(new EtchedBorder(Color.gray, Color.black));

    String[] stuff = {"Overall","Engine", "Transmission", "Infotainment", "Climate", "Communication", "Lighting/Electrical", "Suspension, Tires, Brakes, and Steering"};
    list = new JList(stuff);
    list.setSelectedIndex(0);
    list.addListSelectionListener(new ListSel());

    leftPanel.add(list);

    //Specific Diagnostics List
    rightPanel = new JPanel();
    rightPanel.setLayout(new GridLayout(1,1));
    rightPanel.setSize(300, 800);
    rightPanel.setBackground(Color.white);
    rightPanel.setBorder(new EtchedBorder(Color.gray, Color.black));


      String[] specStats = {"Date","Fuel Economy","Engine Temp", "RPM", "Tire Pressure", "Transmission Status", "Infotainment Status", "Climate Status", "Communication Status", "Lighting/Electrical Status", "Suspension Status", "Brake Status", "Steering Status"};
      specificStats = specStats;
    
    statList = new JList(specificStats);
    statList.setSelectedIndex(0);
    statList.addListSelectionListener(new StatSel());
    
    rightPanel.add(statList);

    // Diagnostics Area
    diagnosticsPanel = new JPanel();
    diagnosticsPanel.setLayout(new BorderLayout());
    GridBagConstraints gbc = new GridBagConstraints();

    diagnosticsPanel.setSize(1200, 150);
    diagnosticsPanel.setBackground(Color.white);
    diagnosticsPanel.setBorder(new EtchedBorder(Color.gray, Color.black));

        File logoFile1 = new File("AutoBiography.png");
    try {
      logo = ImageIO.read(logoFile1);
    } catch (IOException e) {}
    ImageIcon icon1 = new ImageIcon(logo.getScaledInstance(550, 60, 0));
    JLabel logoLabel = new JLabel();
    logoLabel.setIcon(icon1);

    logoPanel = new JPanel();
    logoPanel.setBackground(Color.white);
    logoPanel.setLayout(new GridBagLayout());

    c.anchor = GridBagConstraints.FIRST_LINE_START;
    logoPanel.add(logoLabel);

    c.ipadx = 0;
    c.ipady =0;
    c.gridx = 0;
    c.gridy = 0;
    diagnosticsPanel.add(logoPanel, BorderLayout.NORTH);

    rows = 1;
    cols= 13;
    String [] colNames = {"Date","Fuel Economy","Engine Temp", "RPM", "Tire Pressure", "Transmission Status", "Infotainment Status", "Climate Status", "Communication Status", "Lighting/Electrical Status", "Suspension Status", "Brake Status", "Steering Status"};
    columnNames = colNames;
    sysDisplayed = "O";
    
    myTable = new StatsTable(rows, cols, colNames, sysDisplayed);

    try{
      statRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN = '"+currCar.vin+"'");
        //choice 10
      myTable.setData(dbConnection, currCar);
    }catch(SQLException statE){
      System.out.println("Stat recovery error: "+ statE);
    }
    
    
    myTable.repaint();
    
    paneintheass = new JScrollPane(myTable);
    paneintheass.setPreferredSize(new Dimension(450, 75));
    diagnosticsPanel.add(paneintheass, BorderLayout.SOUTH);

    gbc.ipadx = 0;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.gridx = 0;
    gbc.gridy = 1;
    //diagnosticsPanel.add(table, gbc);
    

    // Car Display Area;
    
    fillerPanel = new JPanel();
    fillerPanel.setSize(600, 300);
    fillerPanel.setBackground(Color.white);
    fillerPanel.setBorder(new EtchedBorder(Color.gray, Color.black));

    fillerLabel = new JTextArea("Date: " +(myTable.getValueAt(0, 0)));
    fillerLabel.setEditable(false);
    fillerPanel.add(fillerLabel);

    JScrollPane scrollPane = new JScrollPane(fillerPanel);
    scrollPane.getVerticalScrollBar();

    middlePanel = new JPanel();
    middlePanel.setLayout(new GridBagLayout());
    middlePanel.setBackground(Color.white);
    middlePanel.setBorder(new EtchedBorder(Color.gray, Color.black));


    c.fill = GridBagConstraints.BOTH;
    c.anchor = GridBagConstraints.PAGE_END;


    c.ipadx = 650;
    c.ipady = 500;
    c.gridx = 0;
    c.gridy = 1;
    middlePanel.add(scrollPane, c);
    c.ipady = 0;

    // Middle Section Layout
    c.gridx = 0;
    c.gridy =0;
    c.ipadx = 70;
    graphicsPanel.add(leftPanel, c);
    
        
    c.ipadx = 0;
    c.ipady = 0;
    c.gridx = 1;
    c.gridy = 0;
    graphicsPanel.add(middlePanel, c);

    c.ipadx = 70;
    c.gridx = 2;
    c.gridy = 0;
    graphicsPanel.add(rightPanel, c);


    // Button Area
    buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(1,1));
    buttonPanel.setSize(1200, 500);
    buttonPanel.setBackground(Color.white);
    buttonPanel.setBorder(new EtchedBorder(Color.gray, Color.black));
    
    upload= new JButton("Upload to Database");
    upload.setSize(100, 50);

    retrieve= new JButton("Retrieve Previous Reading");
    retrieve.addActionListener(theListener);
    retrieve.setSize(100, 50);
    buttonPanel.add(retrieve);
    
    if(!currUser.chID.equals("NULL")){
      gbc.ipady = 0;
      gbc.ipadx = 25;
      gbc.gridx = 0;
      gbc.gridy = 0;
      buttonPanel.add(upload, gbc);
    }

    run = new JButton("Run");
    run.setSize(100, 50);
    gbc.ipadx = 25;
    gbc.gridx = 1;
    gbc.gridy = 0;
    buttonPanel.add(run, gbc);
            
    updatebut = new JButton("Update Info");
    updatebut.setSize(100,50);
    gbc.gridx = 3;
    gbc.gridy = 0;
    buttonPanel.add(updatebut, gbc);

    quit = new JButton("Quit");
    quit.setSize(100, 50);
    gbc.gridx = 2;
    gbc.gridy = 0;
    buttonPanel.add(quit, gbc);
      
      
    upload.addActionListener(theListener);
      updatebut.addActionListener(theListener);
    run.addActionListener(theListener);
    quit.addActionListener(theListener);


    // View Panel
    

    tableRB = new JRadioButton("Text Only", true);
    tableRB.addActionListener(new AutoListener());
    
    graphRB = new JRadioButton("Graph");
    graphRB.addActionListener(new AutoListener());

    viewButtons = new ButtonGroup();
    viewButtons.add(tableRB);
    viewButtons.add(graphRB);
    
    JPanel viewPanel = new JPanel();
    viewPanel.setOpaque(false);
    viewPanel.add(tableRB);
    viewPanel.add(graphRB);

    toWhat="Convert to english";
 
 
    convertButton = new JButton(toWhat);
    
    convertButton.addActionListener(new AutoListener());
    viewPanel.add(convertButton);
        

    //Button Panel and View Panel together
    JPanel buttonView = new JPanel();
    buttonView.setLayout(new GridLayout(2, 1));
    buttonView.setBackground(Color.white);
    buttonView.add(viewPanel);
    buttonView.add(buttonPanel);

    // Window Setup
    mainWindow= new JFrame("AutoBiography");
    mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    thePane= mainWindow.getContentPane();
    thePane.setLayout(new BorderLayout());

    GridBagConstraints mc = new GridBagConstraints();

    mc.fill = GridBagConstraints.BOTH;
    mc.gridx = 0;
    mc.gridy = 0;;
    thePane.add(diagnosticsPanel, BorderLayout.NORTH);

    mc.ipadx = 0;
    mc.gridx = 0;
    mc.gridy = 1;
    thePane.add(graphicsPanel,BorderLayout.CENTER);

    mc.gridx = 0;
    mc.gridy = 2;
    thePane.add(buttonView,BorderLayout.SOUTH);

    mainWindow.setSize(1200, 800);
    mainWindow.setJMenuBar(menuBar);

    mainWindow.setVisible(true);
    watchTable = new Thread();
	listSelector = new Thread();
	listSelector.start();
   // watchTable.start();
  }

  private class AutoListener implements ActionListener {
    public void actionPerformed(ActionEvent e){
       if(e.getSource() == pink){
        thePane.setBackground(Color.PINK);
        thePane.repaint();
      }
      else if (e.getSource() == cyan){
        thePane.setBackground(Color.CYAN);
        thePane.repaint();
      }
      else if (e.getSource() == blue){
        thePane.setBackground(Color.BLUE);
        thePane.repaint();
      }
      else if (e.getSource() == green){
        thePane.setBackground(Color.GREEN);
        thePane.repaint();
      }
      else if (e.getSource() == orange){
        thePane.setBackground(Color.ORANGE);
        thePane.repaint();
      }
      else if (e.getSource() == lightGray){
        thePane.setBackground(Color.LIGHT_GRAY);
        thePane.repaint();
      }

      else if(e.getSource() == upload){
        try{
          statRS=stmt.executeQuery("SELECT * FROM STATS WHERE VIN = '"+currCar.vin+"'");
            //choice 10 Response has no last command
          if(statRS.last()){
            String updateString = "INSERT INTO CLEARINGHOUSE (RPM, ENGINE_TEMP, TIRE_PRESSURE, FUEL_ECONOMY, MILEAGE, OIL_LIFE, FUEL_LEVEL, TRANS_STATUS, TIME_IN_N, TIME_IN_D, TIME_IN_R, TIME_IN_1, TIME_IN_2, TIME_IN_3, INFO_STATUS, RADIO_FREQ, CONNECTED, CD, IPOD, INTERNAL_TEMP, EXTERNAL_TEMP, FAN_SPEED, CLIMATE_STATUS, PHONE_CON, CALL_TIME, COM_STATUS, HEADLIGHT_STATUS, POWER_OUTLETS, INTERNAL_LIGHTS, SUSP_STATUS, BRAKE_FLUID_LIFE, BRAKE_STATUS, STEERING_STATUS, ORDER_NUM, DATE_TIME, CH_ID, VIN) VALUES ("+statRS.getInt("RPM")+", "+ statRS.getInt("ENGINE_TEMP")+", "+ statRS.getInt("TIRE_PRESSURE")+", "+ statRS.getFloat("FUEL_ECONOMY")+", "+ statRS.getInt("MILEAGE")+", "+ statRS.getFloat("OIL_LIFE")+", "+ statRS.getFloat("FUEL_LEVEL")+", '"+ statRS.getString("TRANS_STATUS")+"', "+ statRS.getFloat("TIME_IN_N")+", "+ statRS.getFloat("TIME_IN_D")+", "+ statRS.getFloat("TIME_IN_R")+", "+ statRS.getFloat("TIME_IN_1")+", "+ statRS.getFloat("TIME_IN_2")+", "+ statRS.getFloat("TIME_IN_3")+", '"+ statRS.getString("INFO_STATUS")+"', "+ statRS.getFloat("RADIO_FREQ")+", '"+ statRS.getString("CONNECTED")+"', '"+ statRS.getString("CD")+"', '"+ statRS.getString("IPOD")+"', "+ statRS.getInt("INTERNAL_TEMP")+", "+ statRS.getInt("EXTERNAL_TEMP")+", '"+ statRS.getString("FAN_SPEED")+"', '"+ statRS.getString("CLIMATE_STATUS")+"', '"+ statRS.getString("PHONE_CON")+"', "+ statRS.getInt("CALL_TIME")+", '"+ statRS.getString("COM_STATUS")+"', '"+ statRS.getString("HEADLIGHT_STATUS")+"', '"+ statRS.getString("POWER_OUTLETS")+"', '"+ statRS.getString("INTERNAL_LIGHTS")+"', '"+ statRS.getString("SUSP_STATUS")+"', "+statRS.getInt("BRAKE_FLUID_LIFE")+", '"+ statRS.getString("BRAKE_STATUS")+"', '"+ statRS.getString("STEERING_STATUS")+"', "+ statRS.getInt("ORDER_NUM")+", '"+ statRS.getString("DATE_TIME")+"', '"+currUser.chID+"', '"+ statRS.getString("VIN")+"')";

            stmt.executeUpdate(updateString);
          }
        }catch(SQLException sqlEx){
          System.out.println("Clearinghouse Upload Error: "+ sqlEx );
        }
      }
      else if(e.getSource() == updatebut){
          System.out.println("should bring up update form.");
          new UserUpdateForm(mainWindow, dbConnection, currUser, currCar, selfref);
          System.out.println("should bring up update form.");
      }
      else if(e.getSource() == retrieve){
                
        JFrame oldStatFrame = new JFrame();
        JPanel oldStatPanel = new JPanel();
        oldStatPanel.setLayout(new GridLayout(2, 1));
        oldRecords = new JComboBox();

        ResultSet recordRS;
        try{
          recordRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN='"+currCar.vin+"'");
            //choice 10
                  
          while(recordRS.next()){
            oldRecords.addItem(recordRS.getString("DATE_TIME"));
          }
        }catch(SQLException retE){
          System.out.println("Retrieval Error: "+retE);
        }

        oldStatPanel.add(oldRecords);
        
        recordSubmit = new JButton("Submit");
        oldStatPanel.add(recordSubmit);
        recordSubmit.addActionListener(new AutoListener());

        oldStatFrame.add(oldStatPanel);
        oldStatFrame.pack();
        oldStatFrame.setVisible(true);
        oldStatFrame.setDefaultCloseOperation(2);
      }
      else if (e.getSource() == convertButton){
         //Execute when button is pressed
          if(ntype==1) {
              converte();
              toWhat="Convert to metric";
              System.out.println("English");
              ntype =0;
          }
          else if(ntype==0){
              convertm();
              toWhat="Convert to english";
              System.out.println("Metric");
              ntype=1;
          }
          convertButton.validate();
		                
      } 

      else if(e.getSource() == run){

        rows++;

        myTable = new StatsTable(rows, cols, columnNames, sysDisplayed);
        
        String testString = "test"+rows;
        br = new bluereader();
        ArrayList<String> carVals = br.bluetoothreader(testString, dbConnection, currCar);
        //IA.checkData(carVals);
        
        myTable.setData(dbConnection, currCar);
        
        JScrollPane newSP = new JScrollPane(myTable);
        newSP.setPreferredSize(new Dimension(450, 75));

        diagnosticsPanel.removeAll();
        diagnosticsPanel.add(logoPanel, BorderLayout.NORTH);
        diagnosticsPanel.add(newSP, BorderLayout.SOUTH);
        diagnosticsPanel.validate();
        diagnosticsPanel.repaint();

      }
      else if(e.getSource() == retrieve)
      {
        populate = new Thread();
        pop = true;
        populate.start();
        
        System.out.println("retrieving data");
      }
      
      //else if(e.getSource() == delete)

      else if (e.getSource() == settings){
        new UserUpdateForm(mainWindow, dbConnection, currUser, currCar, selfref);
      }
      else if(e.getSource() == tableRB){
        GridBagConstraints c = new GridBagConstraints();
        middlePanel.removeAll();
        c.gridx = 0;
        c.gridy = 0;
        c.ipady = 500;
        c.ipadx = 550;
        middlePanel.add(fillerPanel, c);
        middlePanel.validate();
      }
      else if(e.getSource() == graphRB){
        GridBagConstraints c = new GridBagConstraints();
        JPanel p = new GraphingData();
        middlePanel.removeAll();
        c.gridx=0;
        c.gridy=0;
        c.ipady = 300;
        c.ipadx = 300;
        middlePanel.add(p, c);
        c.ipadx= 450;
        c.gridy=1;
        c.ipady=100;
        middlePanel.add(fillerPanel,c);
        middlePanel.validate();
      }


      else if(e.getSource() == quitGUI){
        System.exit(0);
      }
      else if(e.getSource() == quit){
        System.exit(0);
      }
      else if(e.getSource() == recordSubmit){
        rows = 1;
        myTable = new StatsTable(rows, cols, columnNames, sysDisplayed);

        try{
          statRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN='"+currCar.vin+"'");
            //choice 10
          myTable.setOldData(statRS, selfref);
        }catch(SQLException ee){}

        JScrollPane newSP = new JScrollPane(myTable);
        newSP.setPreferredSize(new Dimension(450, 75));

        diagnosticsPanel.removeAll();
        diagnosticsPanel.add(logoPanel, BorderLayout.NORTH);
        diagnosticsPanel.add(newSP, BorderLayout.SOUTH);
        diagnosticsPanel.validate();
        diagnosticsPanel.repaint();
      }
    }
  }
  
  private class ComboListener implements ActionListener{
    public void actionPerformed(ActionEvent e0){
      File carFile, newTFile;
      JComboBox jcb = (JComboBox)e0.getSource();
      System.out.println(jcb.getSelectedItem());
      if(jcb.getSelectedItem() == "Ford F-150"){
        //   System.out.println("Foo");
        carFile = new File("F-150.jpg");
        newTFile = new File("Table.png");
      }
      else{
        carFile = new File("Buick.jpeg");
        newTFile = new File("BuickTable.png");
      }
      try {
        car = ImageIO.read(carFile);
      } catch (IOException e3) {}
      ImageIcon carIcon = new ImageIcon(car.getScaledInstance(500, 350, 0));
      carPic.setIcon(carIcon);
      carPic.validate();

     /* try{
        tablePic2 = ImageIO.read(newTFile);
      }catch (IOException e7){}
      ImageIcon newTableIcon = new ImageIcon(tablePic2.getScaledInstance(800, 150, 0));
      table.setIcon(newTableIcon);
      table.validate();
	   */
      mainWindow.validate();
    }
  }
  public void run()
  {
	  //synchronized(this){
		  System.out.println("started thread");
	  while(running)
	  {
		  if(Thread.currentThread()== watchTable)
		  {
		  boolean changes = false;

		  for(int i = 0; i < oldTable.length; i++)
		  {
		  	for(int j = 0; j <oldTable[i].length;j++)
		  	{
		  		Object obj = getData(myTable,i,j);
		  		oldTable[i][j] = (String)obj;
		  	}
		  }
		   if(oldTable.length != newTable.length && oldTable[0].length != newTable[0].length)
		   {
				newTable = oldTable;
		   }
		  for(int i = 0; i < oldTable.length; i++)
		  {
			for(int j = 0; j <oldTable[i].length;j++)
			{
				if(oldTable[i][j]!=newTable[i][j])
				{
					changes = true;
					newTable[i][j] = oldTable[i][j];
				}
			}
		  }
		  if(changes)
		  {
			//upload to database
		  }
	  	}
	  	else if (Thread.currentThread() == populate)
	  	{
			  while(pop)
			  {
				   //get data from database to set table
			  }
		}
		else if(Thread.currentThread() == listSelector)
		{
				//System.out.println(list.getSelectedIndex());
				System.out.println("in here??");
		}

	  }
 // }

  }

  public class ListSel implements ListSelectionListener {
      public void valueChanged(ListSelectionEvent e) {
         int index = ((JList)(e.getSource())).getMinSelectionIndex();
         if(index == 0){
           // Overall
               cols= 13;
               String [] colNames = {"Date","Fuel Economy","Engine Temp", "RPM", "Tire Pressure", "Transmission Status", "Infotainment Status", "Climate Status", "Communication Status", "Lighting/Electrical Status", "Suspension Status", "Brake Status", "Steering Status"};
               columnNames = colNames;
               sysDisplayed = "O";
               
               myTable = new StatsTable(rows, cols, columnNames, sysDisplayed);

               try{
                 statRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN = '"+currCar.vin+"'");
                   //choice 10
                 myTable.setData(dbConnection, currCar);
               }catch(SQLException oE){
                 System.out.println("O query error: "+oE);
               }

               JScrollPane newSP = new JScrollPane(myTable);
               newSP.setPreferredSize(new Dimension(450, 75));
               
               diagnosticsPanel.removeAll();
               diagnosticsPanel.add(logoPanel, BorderLayout.NORTH);
               diagnosticsPanel.add(newSP, BorderLayout.SOUTH);
               diagnosticsPanel.validate();
               diagnosticsPanel.repaint();
               
               statList.removeAll();

               specificStats = colNames;
               
               rightPanel.removeAll();
               statList = new JList(specificStats);
               statList.addListSelectionListener(new StatSel());
               rightPanel.add(statList);
               rightPanel.validate();
               rightPanel.repaint();
         }
         else if(index == 1){
           // Engine
           cols= 7;
           String [] colNames = {"Date","Engine Temp", "RPM","Mileage", "Fuel Economy", "0il Life", "Fuel Volume"};
           columnNames = colNames;
           sysDisplayed = "E";
           
           myTable = new StatsTable(rows, cols, columnNames, sysDisplayed);

           try{
             statRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN = '"+currCar.vin+"'");
               //choice 10
             myTable.setData(dbConnection, currCar);
           }catch(SQLException eE){
             System.out.println("E query error: "+eE);
           }
             
           JScrollPane newSP = new JScrollPane(myTable);
           newSP.setPreferredSize(new Dimension(450, 75));
           
           diagnosticsPanel.removeAll();
           diagnosticsPanel.add(logoPanel, BorderLayout.NORTH);
           diagnosticsPanel.add(newSP, BorderLayout.SOUTH);
           diagnosticsPanel.validate();
           diagnosticsPanel.repaint();
           
           
           specificStats = colNames;
           
           rightPanel.removeAll();
           statList = new JList(specificStats);
           statList.addListSelectionListener(new StatSel());
           rightPanel.add(statList);
           rightPanel.validate();
           rightPanel.repaint();
         }
         else if(index == 2){
           //Transmission
               cols= 8;
               String [] colNames = {"Date", "Transmission Status", "Time in N", "Time in D", "Time in R", "Time in 1", "Time in 2", "Time in 3"};
               columnNames = colNames;
               sysDisplayed = "T";
               
               myTable = new StatsTable(rows, cols, columnNames, sysDisplayed);

               try{
                 statRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN = '"+currCar.vin+"'");
                   //choice 10
                 myTable.setData(dbConnection, currCar);
               }catch(SQLException tE){
                 System.out.println("T query error: "+tE);
               }

               JScrollPane newSP = new JScrollPane(myTable);
               newSP.setPreferredSize(new Dimension(450, 75));
               
               diagnosticsPanel.removeAll();
               diagnosticsPanel.add(logoPanel, BorderLayout.NORTH);
               diagnosticsPanel.add(newSP, BorderLayout.SOUTH);
               diagnosticsPanel.validate();
               diagnosticsPanel.repaint();

               specificStats = colNames;
               
               rightPanel.removeAll();
               statList = new JList(specificStats);
               statList.addListSelectionListener(new StatSel());
               rightPanel.add(statList);
               rightPanel.validate();
               rightPanel.repaint();
         }
         else if(index == 3){
           // Infotainment
               cols= 6;
               String [] colNames = {"Date","Infotainment Status", "Connected", "Radio Frequency", "CD Inserted", "iPod Connected"};
               columnNames = colNames;
               sysDisplayed = "I";
               
               myTable = new StatsTable(rows, cols, columnNames, sysDisplayed);

               try{
                  statRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN = '"+currCar.vin+"'");
                   //choice 10;
                 myTable.setData(dbConnection, currCar);
               }catch(SQLException iE){
                 System.out.println("I query error: "+iE);
               }

               JScrollPane newSP = new JScrollPane(myTable);
               newSP.setPreferredSize(new Dimension(450, 75));
               
               diagnosticsPanel.removeAll();
               diagnosticsPanel.add(logoPanel, BorderLayout.NORTH);
               diagnosticsPanel.add(newSP, BorderLayout.SOUTH);
               diagnosticsPanel.validate();
               diagnosticsPanel.repaint();

               specificStats = colNames;
               
               rightPanel.removeAll();
               statList = new JList(specificStats);
               statList.addListSelectionListener(new StatSel());
               rightPanel.add(statList);
               rightPanel.validate();
               rightPanel.repaint();
         }

         else if(index == 4){
           //Climate
               cols= 5;
               String [] colNames = {"Date","Internal Temp", "External Temp", "Fan Speed", "Climate Status"};
               columnNames = colNames;
               sysDisplayed = "Cl";
               
               myTable = new StatsTable(rows, cols, columnNames, sysDisplayed);
               
               try{
                 statRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN = '"+currCar.vin+"'");
                   //choice 10
                 myTable.setData(dbConnection, currCar);
               }catch(SQLException clE){
                 System.out.println("Cl query error: "+clE);
               }

               JScrollPane newSP = new JScrollPane(myTable);
               newSP.setPreferredSize(new Dimension(450, 75));
               
               diagnosticsPanel.removeAll();
               diagnosticsPanel.add(logoPanel, BorderLayout.NORTH);
               diagnosticsPanel.add(newSP, BorderLayout.SOUTH);
               diagnosticsPanel.validate();
               diagnosticsPanel.repaint();

               specificStats = colNames;
               
               rightPanel.removeAll();
               statList = new JList(specificStats);
               statList.addListSelectionListener(new StatSel());
               rightPanel.add(statList);
               rightPanel.validate();
               rightPanel.repaint();
         } 
         
         else if(index == 5){
           //Communication
               cols= 4;
               String [] colNames = {"Date","Phone Connected", "Total Call Time", "Communication Status"};
               columnNames = colNames;
               sysDisplayed= "Co";

               myTable = new StatsTable(rows, cols, columnNames, sysDisplayed);

               try{
                 statRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN = '"+currCar.vin+"'");
                   //choice 10
                 myTable.setData(dbConnection, currCar);
               }catch(SQLException coE){
                 System.out.println("Co query error: "+coE);
               }

               JScrollPane newSP = new JScrollPane(myTable);
               newSP.setPreferredSize(new Dimension(450, 75));
               
               diagnosticsPanel.removeAll();
               diagnosticsPanel.add(logoPanel, BorderLayout.NORTH);
               diagnosticsPanel.add(newSP, BorderLayout.SOUTH);
               diagnosticsPanel.validate();
               diagnosticsPanel.repaint();

               specificStats = colNames;
               
               rightPanel.removeAll();
               statList = new JList(specificStats);
               statList.addListSelectionListener(new StatSel());
               rightPanel.add(statList);
               rightPanel.validate();
               rightPanel.repaint();
         } 
         else if(index == 6){
           //Leighting & Electrical
               cols= 4;
               String [] colNames = {"Date","Headlight Status", "Power Outlets Status", "Internal Light Status"};
               columnNames = colNames;
               sysDisplayed = "LE";

               myTable = new StatsTable(rows, cols, columnNames, sysDisplayed);
               
               try{
                 statRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN = '"+currCar.vin+"'");
                   //choice 10
                 myTable.setData(dbConnection, currCar);
               }catch(SQLException leE){
                 System.out.println("LE query error: "+leE);
               }

               JScrollPane newSP = new JScrollPane(myTable);
               newSP.setPreferredSize(new Dimension(450, 75));
               
               diagnosticsPanel.removeAll();
               diagnosticsPanel.add(logoPanel, BorderLayout.NORTH);
               diagnosticsPanel.add(newSP, BorderLayout.SOUTH);
               diagnosticsPanel.validate();
               diagnosticsPanel.repaint();

               specificStats = colNames;
               
               rightPanel.removeAll();
               statList = new JList(specificStats);
               statList.addListSelectionListener(new StatSel());
               rightPanel.add(statList);
               rightPanel.validate();
               rightPanel.repaint();
         } 
         else if(index == 7){
           // Tires, Brakes, and Steering
               cols= 6;
               String [] colNames = {"Date","Tire Pressure", "Suspension Status", "Brake Status", "Steering Status", "Brake Fluid Life"};
               columnNames = colNames;
               sysDisplayed = "TSB";

               myTable = new StatsTable(rows, cols, columnNames, sysDisplayed);
               
               try{
                 statRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN = '"+currCar.vin+"'");
                   //choice 10
                 myTable.setData(dbConnection, currCar);
               }catch(SQLException tbsE){
                 System.out.println("TBS query error: "+tbsE);
               }

               JScrollPane newSP = new JScrollPane(myTable);
               newSP.setPreferredSize(new Dimension(450, 75));
               
               diagnosticsPanel.removeAll();
               diagnosticsPanel.add(logoPanel, BorderLayout.NORTH);
               diagnosticsPanel.add(newSP, BorderLayout.SOUTH);
               diagnosticsPanel.validate();
               diagnosticsPanel.repaint();
               
               specificStats = colNames;
               
               rightPanel.removeAll();
               statList = new JList(specificStats);
               statList.addListSelectionListener(new StatSel());
               rightPanel.add(statList);
               rightPanel.validate();
               rightPanel.repaint();
         } 
      }
  }

   public class StatSel implements ListSelectionListener {
      public void valueChanged(ListSelectionEvent e) {
        String labelString="";
         int index = ((JList)(e.getSource())).getMinSelectionIndex();
         for(int i=0; i<specificStats.length; i++){
           if(index == i){
             for(int j=0; j<rows; j++){
               labelString+=(String)(((JList)(e.getSource())).getSelectedValue())+": " + myTable.getValueAt(j, i)+"\n";
             }
             fillerLabel.setText(labelString);
             fillerLabel.validate();
           }
         }
      }
  }

     public void setUser(User inuse){
                currUser = inuse;
        }

  public Object getData(JTable tab, int r, int c)
  {
    return tab.getModel().getValueAt(r,c);
  }

  public void converte()
  {
    try{
      statRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN = '"+currCar.vin+"'");
      if(statRS.last()){
        double fuelEconomy=LtGal(statRS.getFloat("FUEL_ECONOMY"));
        int engineTemp = CtF(statRS.getInt("ENGINE_TEMP"));
        int tirePressure = AtmtPsi(statRS.getInt("TIRE_PRESSURE"));
        int IntTemp=CtF(statRS.getInt("INTERNAL_TEMP"));
        int ExtTemp=CtF(statRS.getInt("EXTERNAL_TEMP"));
        int mileage = KmtMi(statRS.getInt("MILEAGE"));
      }
    }catch(SQLException convE){
      System.out.println("English conversion update error: "+convE);
    }
  }
  
  public int KmtMi(int K)
  {
    K=(int)(K/0.621371192);
    return K;
  }
  
  public double LtGal(double L)
  {
    L=L/0.264172052;
    return L;
  }
  
  public int CtF(int C)
  {
    C=(C*(9/5)) + 32;
    return C;
  }
  
  public int AtmtPsi(int A)
  {
    A=A*6894;
    return A;	
  }
  
  public void convertm()
  {
        try{
      statRS = stmt.executeQuery("SELECT * FROM STATS WHERE VIN = '"+currCar.vin+"'");
      
      double fuelEconomy=GaltL(statRS.getFloat("FUEL_ECONOMY"));
      int engineTemp = FtC(statRS.getInt("ENGINE_TEMP"));
      int tirePressure = PsitAtm(statRS.getInt("TIRE_PRESSURE"));
      int IntTemp=FtC(statRS.getInt("INTERNAL_TEMP"));
      int ExtTemp=FtC(statRS.getInt("EXTERNAL_TEMP"));
      int mileage = MitKm(statRS.getInt("MILEAGE"));
    }catch(SQLException convE){
      System.out.println("English conversion update error: "+convE);
    }
  }
  
  public int MitKm(int K)
  {
    K=(int)(K*0.621371192);
    return K;
  }
  
  public double GaltL(double L)
  {
    L=L*0.264172052;
    return L;
  }
  
  public int FtC(int F){
    F=5*(F-32)/9;
    return F;
  }

  public int PsitAtm(int A)
  {
    A=A/6894;
    return A;	
  }

public static void main(String[] args) throws IOException{
  
  String connectString = "jdbc:mysql://ec2-184-73-238-96.compute-1.amazonaws.com:3008/AutoBiography";
  String driver = "com.mysql.jdbc.Driver";
  String userid = "Team_AutoLytics";
  String pwd = "COE1186";
  Statement stmnt = null;
  ResultSet r = null;
  Connection dConnection = null;
  // Establishing a connection with our online database.
  try{
    Class.forName(driver).newInstance();
    dConnection = DriverManager.getConnection(connectString, userid, pwd);
    stmnt =  dConnection.createStatement();
    System.out.println("Connection successful");
  }catch(Exception e){
    System.out.println("Connection Error.");
    System.out.println(e);
    System.exit(0);
  }
  //new AutoBiographyGUI(new User("), dConnection);
}
  
}